package dtec.project.whereareu;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class UserData extends SQLiteOpenHelper {
	private static final String DB_NAME="data.db";
	static final String TB_NAME="Userdata";
	public static final String COLUMN1="_id";
	public static final String COLUMN2="name";
	private static final int version=1;
	public UserData(Context context) {
		super(context, DB_NAME, null, version);
		// TODO Auto-generated constructor stub
	}
	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		db.execSQL("CREATE  TABLE "+TB_NAME+" ("+COLUMN1+" INTEGER PRIMARY KEY NOT NULL , "+COLUMN2+" VARCHAR NOT NULL )");
	}
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
	
	}
	//FOR LOGOUT
	public boolean logoutUser(int id){
		SQLiteDatabase db = this.getWritableDatabase();
		db.delete(TB_NAME, COLUMN1 + "= ?",new String[]{String.valueOf(id)});
		return true;

	}
	
	public int getUserID(){
		int id=0;
		SQLiteDatabase db=this.getReadableDatabase();
		String sql="SELECT * FROM "+TB_NAME+" ORDER BY "+COLUMN1+" DESC";
		Cursor c=db.rawQuery(sql, null);
		if(c.getCount()>0){
			c.moveToFirst();
			id=c.getInt(c.getColumnIndex(COLUMN1));	
		}

		return id;
	}
	// insert data from server
	public long setUserData(int uid,String name){
		SQLiteDatabase db=this.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put(COLUMN1, uid);
		values.put(COLUMN2, name);
		long id = db.insert(TB_NAME, null, values);

		return id;
	}
	//show user data
	public Cursor getUserData(){
		SQLiteDatabase db=this.getReadableDatabase();
		String sql="SELECT * FROM "+TB_NAME+" ORDER BY "+COLUMN1+" DESC";
		Cursor c=db.rawQuery(sql, null);

		return c;
	}
	
	public boolean checkStatus(){
		boolean flag=false;
		SQLiteDatabase db=this.getReadableDatabase();
		long count=DatabaseUtils.queryNumEntries(db,TB_NAME);
		if(count!=0){
			flag=true;
		}

		return flag;
	}
	
	public String getUsername(){
		String id=null;
		SQLiteDatabase db=this.getReadableDatabase();
		String sql="SELECT * FROM "+TB_NAME+" ORDER BY "+COLUMN1+" DESC";
		Cursor c=db.rawQuery(sql, null);
		if(c.getCount()>0){
			c.moveToFirst();
			id=c.getString(c.getColumnIndex(COLUMN2));	
		}

		return id;
	}
	

}
